package com.jp.kefu.service;

import com.jp.kefu.web.proxy.response.AccessToken;
import com.jp.kefu.web.proxy.ApiProxy;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * 获取AccessToken
 * @author lijin
 */
@Service
public class TokenService extends BaseService{
    private static final String GRANT_TYPE = "client_credential";
    private static final String APP_ID = "wxec41e4aa27e5a443";
    private static final String APP_SECRET = "8ceffe22725a6267d928804576ddb550";
    private static final String URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type={grant_type}&appid={appid}&secret={secret}";

    @Autowired
    private ApiProxy proxy;

    private String accessToken = "";
    public String getToken() {
        if(StringUtils.isBlank(accessToken))refreshToken();
	   return accessToken;
    }

    //刷新token
    public void refreshToken(){
        HashMap<String, String> uriVariables = new HashMap<>();
        uriVariables.put("grant_type", GRANT_TYPE);
        uriVariables.put("appid", APP_ID);
        uriVariables.put("secret", APP_SECRET);
        AccessToken response = proxy.send(HttpMethod.GET, URL, null, AccessToken.class, uriVariables);
        accessToken = response.getAccessToken();


    }
}
